import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {userStore} from "@/stores/user.ts"
import {rightStore} from "@/stores/rights.ts"
//vite提供给我们一个导入文件的方法
const comlist=import.meta.glob("@/views/twoviews/*.vue")
console.log(comlist)
//获取到用户的信息
function getToken(){
  const store=userStore()
  let token=""
  //如果变量对象不空的话  取到token
  if(Object.keys(store.user).length!=0){
      token=store.user.token;
  }
  return token
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children:[
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('../views/twoviews/Welcome.vue')
        },
        {
          path:"/",
          redirect:"/welcome"
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
        path: '/:catchAll(.*)',
        name: '404',
        component: () => import('../views/404.vue'),
    }
  ]
})

//做一个开关
let flag=true
router.beforeEach((to,from,next)=>{
  if(to.path!="/login"){
    //首页  ---看token在不在
    let token=getToken()
    if(!token){
      //提示用户进行登录
      ElMessage.error('请先登录');
      next('/login')
    }else{
      //将pinia中的rights数据拿到  如果有数据需要将这些数据配置成动态的路由
      const store=rightStore()
      if(flag&&store.rightlist.length>0){
        //做一些处理
        store.rightlist.forEach(item=>{
          let newname=item.path.charAt(0).toUpperCase()+item.path.substring(1,item.path.length-1)+"s"
          let obj={}
          obj.path="/"+item.path
          obj.name=item.path
          obj.component=comlist[`/src/views/twoviews/${newname}.vue`]

          //将遍历到的对象追加到router中
          router.addRoute("home",obj)
        })
        flag=false;
        next({path:to.fullPath})
        console.log(456)
      }else{
        console.log(123)
        next()
      }
    }
    
  }else{
    //除了首页
    next()
  }

})

export default router
